package com.chuanyang.driverh.mainhome;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainhome.adapter.GoodsForAssignWaybilDetailAdapter;
import com.chuanyang.driverh.mainorder.SureUnLoadOverActivity;
import com.chuanyang.driverh.mainother.BeforeNaviActivity;
import com.chuanyang.driverh.mainother.LookPhotoDetailActivity;
import com.chuanyang.driverh.response2.ResultWaitTransDriver;
import com.chuanyang.driverh.response2.ResultWaybilInfoTop;
import com.chuanyang.driverh.responseresult.LookWaybillDetailData;
import com.chuanyang.driverh.responseresult.LookWaybillDetailResult;
import com.chuanyang.driverh.responseresult.OrderAddressResult;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.responseresult.ValidateCodeResult;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshActivityEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class WaybilDetailDirverActivity extends BaseTitleActivity {

    private TextView tv_waybill_no;
    private TextView tv_date;
    private TextView tv_driver_name;
    private TextView tv_plate_no;
    private TextView tv_order_status;
    private TextView tv_tel;
    private TextView tv_tel_dial;
    private TextView tv_gua_weight;
    private TextView tv_shi_weight;
    private TextView tv_gua_num;
    private TextView tv_shi_num;
    private TextView tv_all_price;
    private ListView lv_goods;
    private TextView tv_left;
    private TextView tv_confirm;
    private LinearLayout ll_photo_out;
    private LinearLayout ll_photo;
    private Dialog dialog;
    private String waybilId = "";
    ResultWaitTransDriver.OutDataEntity.DataEntity.PageWayBillListEntity waitTransEntity;
    ResultWaybilInfoTop.DataBean waybilDetail;
    private int waybilStatus;//运单状态
    private int type;//0,默认，消息进入或，收款跟踪进入，不显示按钮和状态，1,代运实发进入，车队长分配的单子。需要显示按钮。2，代运实发进入，个人接的单子
    private AlertDialog alertDialog;
    private EditText et_sureunload_code;
    private TextView tv_cancle_unload;
    private TextView tv_sureunload_getcode;
    private TextView tv_sure_unload;
    private boolean validateOk;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://分配的运单确认收货
                    updateWaybillUnload((String) msg.obj, true);
                    break;
                case 2://司机的个人订单确认收货
                    updateWaybillUnload((String) msg.obj, false);
                    break;
            }
        }
    };

    @Override
    protected int getContentResId() {
        return R.layout.home_act_waibil_detail_no_top;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        View view=View.inflate(activityContext,R.layout.home_item_waybil_top,null);

        tv_waybill_no = (TextView) view.findViewById(R.id.tv_waybill_no);
        tv_date = (TextView)view. findViewById(R.id.tv_date);
        tv_driver_name = (TextView)view. findViewById(R.id.tv_driver_name);
        tv_plate_no = (TextView)view. findViewById(R.id.tv_plate_no);
        tv_order_status = (TextView) view.findViewById(R.id.tv_order_status);
        tv_tel = (TextView)view. findViewById(R.id.tv_tel);
        tv_tel_dial = (TextView) view.findViewById(R.id.tv_tel_dial);
        tv_gua_weight = (TextView)view. findViewById(R.id.tv_gua_weight);
        tv_shi_weight = (TextView)view. findViewById(R.id.tv_shi_weight);
        tv_gua_num = (TextView)view. findViewById(R.id.tv_gua_num);
        tv_shi_num = (TextView)view. findViewById(R.id.tv_shi_num);
        tv_all_price = (TextView) view.findViewById(R.id.tv_all_price);
        ll_photo_out = (LinearLayout)view. findViewById(R.id.ll_photo_out);
        ll_photo = (LinearLayout)view. findViewById(R.id.ll_photo);

        tv_left = (TextView) findViewById(R.id.tv_left);
        tv_confirm = (TextView) findViewById(R.id.tv_confirm);
        lv_goods = (ListView) findViewById(R.id.lv_goods);
        lv_goods.addHeaderView(view);
    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("运单详情");
        getRightTextView().setText("状态");
        waybilId = getIntent().getStringExtra("waybilId");
        type = getIntent().getIntExtra("type", 0);

        //0,默认，消息进入或，收款跟踪进入，不显示按钮和状态，1,代运实发进入，需要显示按钮。2，代运实发，个人单进入，
        if (type == 0) {
            tv_confirm.setVisibility(View.GONE);
            tv_left.setVisibility(View.GONE);
        } else {
            waitTransEntity = (ResultWaitTransDriver.OutDataEntity.DataEntity.PageWayBillListEntity) getIntent().getSerializableExtra("data");
        }

        getTopData();
        getGoodsData();
    }

    private void getTopData() {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybilId);
        MyHttpUtil.selectWaybillInfo(activityContext, params, new MyCallback<ResultWaybilInfoTop>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ResultWaybilInfoTop result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    waybilDetail = result.getData();
                    if (result.getData().getWaybillStatus() != null) {
                        setBottomButtons(Integer.parseInt(result.getData().getWaybillStatus()));
                    }
                    updateUi(result.getData());
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });

    }

    private void setBottomButtons(int status) {
        waybilStatus = status;
        //0,默认，消息进入或，收款跟踪进入，不显示按钮和状态，1,代运实发进入，车队长分配的单子。需要显示按钮。2，代运实发进入，个人接的单子
        if (type == 0) {
            tv_confirm.setVisibility(View.GONE);
            tv_left.setVisibility(View.GONE);
        } else {//个人司机代运实发进入。
            if (waybilStatus < 4 && waybilStatus > 0) {
                if (type == 1) {
                    if (waitTransEntity != null && waitTransEntity.getApplyNoStatus() == 0) {
                        tv_left.setText("申请放弃");
                        tv_left.setVisibility(View.VISIBLE);
                    } else {
                        tv_left.setVisibility(View.GONE);
                    }
                } else {
                    tv_left.setVisibility(View.GONE);
                }
                tv_confirm.setText("开始运输");
                tv_confirm.setVisibility(View.VISIBLE);
            } else if (waybilStatus == 4) {
                tv_left.setText("导航");
                tv_left.setVisibility(View.VISIBLE);
                tv_confirm.setText("运输完成");
                tv_confirm.setVisibility(View.VISIBLE);
            } else if (waybilStatus == 5) {
                tv_left.setText("导航");
                tv_left.setVisibility(View.VISIBLE);
                tv_confirm.setText("运输完成");
                tv_confirm.setVisibility(View.VISIBLE);
            } else if (waybilStatus == 6) {
                tv_left.setVisibility(View.GONE);
                tv_confirm.setText("验证卸货");
                tv_confirm.setVisibility(View.VISIBLE);
            } else if (waybilStatus == 7) {
                tv_left.setVisibility(View.GONE);
                tv_confirm.setVisibility(View.GONE);
                tv_order_status.setText("已完成");
            } else if (waybilStatus == 8) {
                tv_order_status.setText("已取消");
                tv_left.setVisibility(View.GONE);
                tv_confirm.setVisibility(View.GONE);
            } else {
                tv_left.setVisibility(View.GONE);
                tv_confirm.setVisibility(View.GONE);
            }
        }

    }


    private void getGoodsData() {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybilId);
        MyHttpUtil.selectByWaybillId(activityContext, params, new MyCallback<LookWaybillDetailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(LookWaybillDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    setGoodsAdapter(result.getData());
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }


    private void setGoodsAdapter(LookWaybillDetailData data) {
        List<LookWaybillDetailData.DataBean> ss = data.getData();
        GoodsForAssignWaybilDetailAdapter adapter = new GoodsForAssignWaybilDetailAdapter(activityContext, data.getData());
        lv_goods.setAdapter(adapter);
    }

    private void updateUi(final ResultWaybilInfoTop.DataBean waybildata) {
        if (waybildata == null) return;
        try {
            setTopUi(waybildata);
            setImageView(waybildata);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void setTopUi(ResultWaybilInfoTop.DataBean waybildata) {
        tv_waybill_no.setText(waybildata.getWaybillNo());
        tv_date.setText(waybildata.getOrderTime());
        if (type == 2) {//个人的单子

            tv_driver_name.setText(waybildata.getUsername());
            tv_plate_no.setText("(" + waybildata.getPlateNumber() + ")");
            tv_tel.setText(StringUtil.handlePhoneNumShow(SharedPrefUtil.getPhone()));

        } else {
            if (waybildata.getFleetLeaderName() != null)
                tv_driver_name.setText(waybildata.getFleetLeaderName());
            if (waybildata.getFleetName() != null) {
                tv_plate_no.setText("(" + waybildata.getFleetName() + ")");
            } else {
                tv_plate_no.setText("(" + "null" + ")");
            }
            if (waybildata.getFleetLeaderPhone() != null) {
                tv_tel.setText(StringUtil.handlePhoneNumShow(waybildata.getFleetLeaderPhone()));
            }

        }
        tv_gua_weight.setText(waybildata.getOriginalWeight() + "");
        if (waybildata.getSumDetailsWeight() != 0)
            tv_shi_weight.setText(waybildata.getSumDetailsWeight() + "");
        tv_gua_num.setText(waybildata.getOriginalNum() + "");
        if (waybildata.getSumDetailsNum() != 0)
            tv_shi_num.setText(waybildata.getSumDetailsNum() + "");
        tv_all_price.setText(waybildata.getSumPrice() + "");

        if ("2".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("待装货");
        } else if ("3".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("装货中");
        } else if ("4".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("运输中");
        } else if ("5".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("卸货中");
        } else if ("6".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("待收货");
        } else if ("7".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("已完成");
        } else if ("8".equals(waybildata.getWaybillStatus())) {
            tv_order_status.setText("已取消");
        }

        tv_tel_dial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DialogUtil.dial(activityContext,waybildata.getPhoneCall());
                DialogUtil.dial(activityContext, tv_tel.getText().toString().trim());
            }
        });

    }

    private int imageNum;

    private void setImageView(ResultWaybilInfoTop.DataBean waybildata) {
        if (waybildata != null && waybildata.getWaybillImagesList() != null && waybildata.getWaybillImagesList().size() > 0) {
            imageNum = waybildata.getWaybillImagesList().size();
            ll_photo_out.setVisibility(View.VISIBLE);
            if (ll_photo.getChildCount() > 0) {
                ll_photo.removeAllViews();
            }
            for (final ResultWaybilInfoTop.DataBean.WaybillImagesListBean entity : waybildata.getWaybillImagesList()) {
                addView(entity, 0);
            }
            if (waybildata.getWaybillImagesList().size() < 8) {
                if (type == 1 || type == 2) {
                    //代运实发里有添加按钮
                    addView(null, 1);
                }
            }
        } else {
           /* if (waybilStatus >= 4) {
                ll_photo_out.setVisibility(View.VISIBLE);
                if (ll_photo.getChildCount() > 0) {
                    ll_photo.removeAllViews();
                }
                addView(null, 1);
            } else {
                ll_photo_out.setVisibility(View.GONE);
            }*/



            ll_photo_out.setVisibility(View.VISIBLE);
            if (ll_photo.getChildCount() > 0) {
                ll_photo.removeAllViews();
            }
            addView(null, 1);
        }
    }

    private void addView(final ResultWaybilInfoTop.DataBean.WaybillImagesListBean entity, final int ifShowDelete) {
        //ifShowDelete ==0,显示删除小图片，
        View view = View.inflate(activityContext, R.layout.home_item_imageview, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.img_unload);
        TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(layoutParams);

        if (ifShowDelete == 0 && entity != null) {
            BitmapUtil.showImgForNetPath(entity.getWaybillImages(), imageView);
        } else {
            imageView.setImageResource(R.mipmap.upload);
        }


        if (ifShowDelete == 0 && (type == 1 || type == 2)) {
            tv_delete.setVisibility(View.VISIBLE);
        } else {
            tv_delete.setVisibility(View.GONE);
        }

        ll_photo.addView(view); //动态添加图片
        //查看大图
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ifShowDelete == 0) {
                    Intent intent = new Intent(activityContext, LookPhotoDetailActivity.class);
                    intent.putExtra("data", entity.getWaybillImages());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(activityContext, SureUnLoadOverActivity.class);
                    intent.putExtra("maxNum", 8 - imageNum);
                    intent.putExtra("ifChangeStatus",false);
                    if (waybilDetail != null) {
                     /*   if (StringUtil.isBlank(waybilDetail.getFleetId())) {
                            intent.putExtra("orederId", waybilDetail.getOrderId());
                            intent.putExtra("fromlist", true);
                            intent.putExtra("personalOrder", true);
                        } else {
                            intent.putExtra("waybillId", waybilDetail.getWaybillId());
                            intent.putExtra("fromlist", true);
                            intent.putExtra("personalOrder", false);
                        }*/

                        intent.putExtra("waybillId", waybilDetail.getWaybillId());
                        intent.putExtra("fromlist", true);
                        intent.putExtra("personalOrder", false);

                    } else {
                        return;
                    }
                    startActivity(intent);
                }
            }
        });
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = DialogUtil.myDialog(activityContext, "删除照片", "取消", "确定", "确定删除照片？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.dialog_btn_right) {
                            ArrayList<Integer> images = new ArrayList<Integer>();
                            images.add(entity.getWaybillId());
                            deleteWaybillImgById(images);
                        }
                        dialog.cancel();
                    }
                });
            }
        });


    }

    //删除卸货照片
    private void deleteWaybillImgById(ArrayList<Integer> imageId) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillImgIds", imageId);
        MyHttpUtil.deleteWaybillImgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext, "删除成功");
                    getTopData();
                } else {
                    if (result.getMsg() != null)
                        PrintUtil.toast(activityContext, result.getMsg());
                }

            }
        });
    }


    @Override
    protected void initListener() {
        tv_left.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_left:
                leftClick();

                break;
            case R.id.tv_confirm:
                rightCick();
                break;
        }


    }

    private void leftClick() {
        if (waybilStatus < 4 && waybilStatus > 0) {
            if (type == 1) {
                //放弃订单
                dialog = DialogUtil.myDialog(activityContext, "提示", "取消", "确定", "您是否申请放弃运单?", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.dialog_btn_left:
                                break;
                            case R.id.dialog_btn_right:
                                applyNoWaybill(waybilId + "");
                                break;
                        }
                        dialog.cancel();
                    }
                });

            }
        } else if (waybilStatus == 4) {
            //导航
            if (waitTransEntity != null && waitTransEntity.getOrderId() != 0)
                selectOrderAddress(waitTransEntity.getOrderId() + "");
        } else if (waybilStatus == 5) {
            //导航
            if (waitTransEntity != null && waitTransEntity.getOrderId() != 0)
                selectOrderAddress(waitTransEntity.getOrderId() + "");
        } else if (waybilStatus == 6) {
            //无

        } else if (waybilStatus == 7) {
            //无

        }
    }

    private void rightCick() {
        if (waybilStatus < 4 && waybilStatus > 0) {
            //开始运输
            if (waitTransEntity != null)
                startTranslate(waitTransEntity);

        } else if (waybilStatus == 4 || waybilStatus == 5) {
            //运输完成
            Intent intent = new Intent(activityContext, SureUnLoadOverActivity.class);

            if (waitTransEntity.getFleetId() == 0) {
                intent.putExtra("orederId", waitTransEntity.getOrderId());
                intent.putExtra("fromlist", true);
                intent.putExtra("personalOrder", true);
            } else {
                intent.putExtra("waybillId", waitTransEntity.getWaybillId());
                intent.putExtra("fromlist", true);
                intent.putExtra("personalOrder", false);
            }


           /* intent.putExtra("waybillId", waitTransEntity.getWaybillId());
            intent.putExtra("fromlist", true);
            intent.putExtra("personalOrder", false);*/
            startActivity(intent);

        } else if (waybilStatus == 6) {
            //验证卸货
            if (waitTransEntity.getFleetId() != 0) {
                sureAcceptGood(waitTransEntity.getContactPhone(), waitTransEntity.getWaybillId() + "", true);
            } else {
                sureAcceptGood(waitTransEntity.getContactPhone(), waitTransEntity.getOrderId() + "", false);
            }


        }

    }

    @Override
    protected void baseGoEnsure() {
        Intent intent = new Intent(activityContext, WaybilStatusActivity.class);
        intent.putExtra("waybilId", waybilId + "");
        startActivity(intent);
    }


    /**
     * 司机申请拒绝接受运单
     *
     * @param id
     */
    private void applyNoWaybill(String id) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("waybillId", id);
        MyHttpUtil.applyNoWaybill(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                    tv_left.setVisibility(View.GONE);
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }

    /**
     * 导航请求数据
     *
     * @param id
     */
    private void selectOrderAddress(String id) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", id);
        MyHttpUtil.selectOrderAddress(activityContext, params, new MyCallback<OrderAddressResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(OrderAddressResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent(activityContext, BeforeNaviActivity.class);
                    intent.putExtra("OrderAddressResult", result);
                    startActivity(intent);
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }

    /**
     * 开始运输
     */
    private void startTranslate(ResultWaitTransDriver.OutDataEntity.DataEntity.PageWayBillListEntity order) {
        DialogUtil.showLoadingDialog(activityContext, "请求中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("waybillId", order.getWaybillId() + "");
        params.put("waybillStatus", "4");
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.startTranslate(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    waybilStatus = 4;
                    setBottomButtons(4);
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }

    /**
     * 验证卸货
     *
     * @param phone id
     */
    public void sureAcceptGood(final String phone, final String id, final boolean iswaybill) {

        if (null == alertDialog) {
            alertDialog = new AlertDialog.Builder(activityContext).create();
            alertDialog.show();
            alertDialog.setTitle(null);
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    alertDialog = null;
                }
            });
            Window window = alertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawable(new ColorDrawable(0));
            window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setContentView(R.layout.dialog_sureunload);
            View view = window.getDecorView();
            et_sureunload_code = (EditText) view.findViewById(R.id.et_sureunload_code);
            tv_cancle_unload = (TextView) view.findViewById(R.id.tv_cancle_unload);
            tv_sureunload_getcode = (TextView) view.findViewById(R.id.tv_sureunload_getcode);
            tv_sure_unload = (TextView) view.findViewById(R.id.tv_sure_unload);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    validateOk = false;

                }
            });
            tv_cancle_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
            tv_sureunload_getcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!validateOk) {//获取成功验证码 且对话框没消失时无法多次点击
                        getValidateCode(phone, id);
                    } else {

                        PrintUtil.toast(activityContext, "验证码已发送给货主！");
                    }
                }
            });
            tv_sure_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(et_sureunload_code.getText().toString().trim())) {
                        PrintUtil.toast(activityContext, "请填写获取到验证码");
                        return;
                    }
                    if (!validateOk) {
                        PrintUtil.toast(activityContext, "请先获取验证码");
                        return;
                    }

                    Message message = Message.obtain();
                    message.obj = id;
                    if (iswaybill) {
                        message.what = 1;

                    } else {
                        message.what = 2;

                    }
                    mHandler.sendMessage(message);
//                    alertDialog.dismiss();
//                    alertDialog = null;
                }
            });
        }
        //下面两行代码加入后即可弹出输入法
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    /**
     * 获取验证码
     */
    private void getValidateCode(String phone, String id) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", phone);
        params.put("validateMsg", id);
        MyHttpUtil.getSureValidateCode(activityContext, params, new MyCallback<ValidateCodeResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ValidateCodeResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    validateOk = true;
                    tv_sureunload_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.tv_shape_gray_round_corner_solid));
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }

    /**
     * 收货完成 （传入订单id或者运单id）
     */
    private void updateWaybillUnload(final String waybilOrOrderId, final boolean iswaybill) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        if (iswaybill) {
            params.put("waybillId", waybilOrOrderId);
        } else {
            params.put("orderId", waybilOrOrderId);
        }
        params.put("waybillStatus", "7");
        params.put("validateMsg", waybilOrOrderId + "");
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.updateWaybillStatus(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext, "您已替货主确认收货");
                    waybilStatus = 7;
                    setBottomButtons(7);


                    alertDialog.dismiss();
                    alertDialog = null;

                    if (!iswaybill) {
                        shouhuo(waybilOrOrderId);
                    } else {
                        EventBusUtil.postEvent(new RefleshFragEvent(3));
                    }

                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }

    /**
     * 收货完成 （传入订单id或者运单id）
     */
    private void shouhuo(String id) {//type0运单，1订单
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", id);
        params.put("orderStatus", "7");
        MyHttpUtil.signoff(activityContext, params, new MyCallback<Result>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                } else {
//                    PrintUtil.toast(getActivity(),result.getMsg());
                }
            }
        });


    }


    public void onEventMainThread(RefleshActivityEvent event) {
        if (event.getIndex() == 0) {
            waybilStatus = 6;
            setBottomButtons(6);

        }
    }

    public void onEventMainThread(RefleshFragEvent event) {
        if (event.getIndex() == 3) {
            getTopData();
        }
    }


}
